package org.siqisource.webstart.evolve.shiro;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;

public class DatabaseSessionDAO extends CachingSessionDAO {

	private DataSource dataSource = null;

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}


	@Override
	protected void doUpdate(Session session) {
		String sql = "update sessions set session_object = ? where session_id = ?";
		
		try {
			Connection conn = dataSource.getConnection();
			PreparedStatement psmt = conn.prepareStatement(sql);
			psmt.setObject(1, session);
			psmt.setString(2, session.getId().toString());
			psmt.execute();
			psmt.close();
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	protected void doDelete(Session session) {
		String sql = "delete from sessions  where session_id = ?";
		try {
			Connection conn = dataSource.getConnection();
			PreparedStatement psmt = conn.prepareStatement(sql);
			psmt.setString(1, session.getId().toString());
			psmt.execute();
			psmt.close();
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	protected Serializable doCreate(Session session) {
		Serializable sessionId = generateSessionId(session);
		assignSessionId(session, sessionId);

		String sql = "insert into sessions values (?,?)";
		try {
			Connection conn = dataSource.getConnection();
			PreparedStatement psmt = conn.prepareStatement(sql);
			psmt.setString(1, sessionId.toString());
			psmt.setObject(2, session);
			psmt.execute();
			psmt.close();
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return sessionId;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		String sql = "select session_object from sessions  where session_id = ?";
		try {
			Connection conn = dataSource.getConnection();
			PreparedStatement psmt = conn.prepareStatement(sql);
			psmt.setString(1, sessionId.toString());
			ResultSet rs = psmt.executeQuery();
			if (rs.next()) {
				return (Session) rs.getObject("session_object");
			}
			psmt.close();
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
